﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace orderCreater
{
    public partial class Frm531Order : Form
    {
        public OrderCreaterModel OCM = new OrderCreaterModel(ConfigurationManager.AppSettings["ConnStr-531"]);
        public Frm531Order()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.sr_bgw.WorkerSupportsCancellation = true;
            this.sr_btn_stop.Enabled = false;
            this.sr_tb_goodIds.Text = ConfigurationManager.AppSettings["goodsIds-531Order"];
        }
        
        private void sr_bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            this.sr_btn_start.Enabled = false;
            this.sr_btn_stop.Enabled = true;
            this.sr_tb_goodIds.Enabled = false;
            this.sr_tb_logs.Text = "";
            int count = 0;
            decimal total = 0, total_pay = 0;
            int post_err_cnt = 0;
            StringBuilder _logs = new StringBuilder();
            do
            {
                if (worker.CancellationPending || total > decimal.Parse(this.sr_tb_priceArea.Text))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    if (Int32.Parse(DateTime.Now.Hour.ToString()) >= 8) {
                        ///获取新增用户
                        WDH_REGISTER new_user = cb_user.Checked ? OCM.WSYExistUser() : OCM.WSYNewUser();
                        if (new_user.status == 200)
                        {
                            ///获取收货地址
                            WDH_AddrRange new_addr = OCM.WSYNormalAddr();
                            if (new_addr.status == 200 && new_addr.data.Count > 0)
                            {
                                WSY_Buyer buyer = OCM.WSYGetBuyer(new_user.data.member_id);
                                WSY_Goods goods = OCM.WSYRandGoodsByIds(this.sr_tb_goodIds.Text.ToString());
                                WSY_Shop shop = OCM.WSYRandShop();
                                string orderCode = OCM.CreateOrderCode();
                                string payCode = OCM.createPayCode(new_user.data.member_id);
                                string orderTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                string addressLength = OCM.StringToByte(new_addr.data[0].address, Encoding.UTF8).Length.ToString();
                                if (bd_cb.Checked)
                                {
                                    orderTimeStr = OCM.CreateOrderTime(this.sr_dt_time.Value.ToString("yyyy-MM-dd"));
                                }
                                string orderTime = ((DateTime.Parse(orderTimeStr).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                                string requestTime = ((DateTime.Parse(OCM.CreateSendTime(orderTimeStr)).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                                string orderRemarks = OCM.getWSYOrderRemark();
                                string order_id = "0";
                                if (OCM.IsPay() && total_pay< decimal.Parse(tb_sr_payPrice.Text))
                                {
                                    string payTimeStr = OCM.CreatePayTime(orderTimeStr, tb_jiange.Text);
                                    string payTime = ((DateTime.Parse(payTimeStr).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                                    string payType = "alipay";
                                    string sql_order = "INSERT INTO `db_order` (`order_sn`, `pay_sn`, `store_id`, `store_name`, `buyer_id`, `buyer_name`, `buyer_email`,`add_time`, `payment_code`, `payment_time`, `finnshed_time`, `goods_amount`, `order_amount`, `rcb_amount`, `pd_amount`, `shipping_fee`, `evaluation_state`, `order_state`, `refund_state`, `lock_state`, `delete_state`, `refund_amount`, `delay_time`, `order_from`, `shipping_code`, `request_delivery_time`,`type_status`) VALUES ('"
                                                     + orderCode + "', '" + payCode + "', '" + shop.ID + "', '" + shop.Name + "', '" + new_user.data.member_id + "', '" + buyer.member_name + "', '" + buyer.member_email + "', '" + orderTime + "', '" + payType + "', '" + payTime + "', '0', '" + goods.goods_price + "', '" + goods.goods_price + "', '0.00', '0.00', '0.00', '0', '20', '0', '0', '0', '0.00', '0', '1', '', '" + requestTime + "',2);SELECT LAST_INSERT_ID();";

                                    order_id = OCM.ExecuteMySql(sql_order);
                                    if (order_id != "" && order_id != "-1")
                                    {
                                        if (this.sync_alipay_cb.Checked == true)
                                        {
                                            syncAlipay(orderCode, goods.goods_price, buyer.member_email, buyer.member_name, payTimeStr);
                                        }
                                        string sql_order_common = "INSERT INTO `db_order_common` (`order_id`, `store_id`, `shipping_time`, `shipping_express_id`, `evaluation_time`, `evalseller_state`, `evalseller_time`, `order_message`, `order_pointscount`, `voucher_price`, `voucher_code`, `deliver_explain`, `daddress_id`, `reciver_name`, `reciver_info`, `reciver_province_id`, `reciver_city_id`, `reciver_area_id`,  `invoice_info`, `promotion_info`, `dlyo_pickup_code`) VALUES ('"
                                                                + order_id + "', '" + shop.ID + "', '0', '0', '0', '0', '0', '" + orderRemarks + "', '0', null, null, null, '0', '" + new_addr.data[0].name + "', 'a:6:{s:5:\"phone\";s:11:\"" + new_addr.data[0].mobile + "\";s:9:\"mob_phone\";s:11:\"" + new_addr.data[0].mobile + "\";s:9:\"tel_phone\";s:0:\"\";s:7:\"address\";s:" + addressLength + ":\"" + new_addr.data[0].address + "\";s:4:\"area\";s:0:\"\";s:6:\"street\";s:0:\"\";}', '" + new_addr.data[0].province_id + "', '" + new_addr.data[0].city_id + "', '" + new_addr.data[0].area_id + "', 'a:0:{}', '', null);";
                                        OCM.ExecuteNonSql(sql_order_common);
                                        string sql_order_goods = "INSERT INTO `db_order_goods` (`order_id`, `goods_id`, `goods_name`, `goods_price`, `goods_num`, `goods_image`, `goods_pay_price`, `store_id`, `buyer_id`, `goods_type`, `promotions_id`, `commis_rate`, `gc_id`) VALUES ('" +
                                            order_id + "', '" + goods.goods_id + "', '" + goods.goods_name + "', '" + goods.goods_price + "', '1', '" + goods.goods_image + "', '" + goods.goods_price + "', '" + shop.ID + "', '" + new_user.data.member_id + "', '1', '0', '0', '" + goods.gc_id + "');";
                                        OCM.ExecuteNonSql(sql_order_goods);
                                        string sql_order_pay = "INSERT INTO `db_order_pay` (`pay_sn`, `buyer_id`, `api_pay_state`) VALUES ('" + payCode + "', '" + new_user.data.member_id + "', '1');";
                                        OCM.ExecuteNonSql(sql_order_pay);
                                    }
                                }
                                else
                                {
                                    string sql_order = "INSERT INTO `db_order` (`order_sn`, `pay_sn`, `store_id`, `store_name`, `buyer_id`, `buyer_name`, `buyer_email`, `add_time`, `payment_code`, `payment_time`, `finnshed_time`, `goods_amount`, `order_amount`, `rcb_amount`, `pd_amount`, `shipping_fee`, `evaluation_state`, `order_state`, `refund_state`, `lock_state`, `delete_state`, `refund_amount`, `delay_time`, `order_from`, `shipping_code`, `request_delivery_time`,`type_status`) VALUES ('"
                                                    + orderCode + "', '" + payCode + "', '" + shop.ID + "', '" + shop.Name + "', '" + new_user.data.member_id + "', '" + buyer.member_name + "', '" + buyer.member_email + "', '" + orderTime + "', 'online', '0', '0', '" + goods.goods_price + "', '" + goods.goods_price + "', '0.00', '0.00', '0.00', '0', '10', '0', '0', '0', '0.00', '0', '1', '', '" + requestTime + "',2);SELECT LAST_INSERT_ID();";
                                    order_id = OCM.ExecuteMySql(sql_order);
                                    if (order_id != "" && order_id != "-1")
                                    {
                                        string sql_order_common = "INSERT INTO `db_order_common` (`order_id`, `store_id`, `shipping_time`, `shipping_express_id`, `evaluation_time`, `evalseller_state`, `evalseller_time`, `order_message`, `order_pointscount`, `voucher_price`, `voucher_code`, `deliver_explain`, `daddress_id`, `reciver_name`, `reciver_info`, `reciver_province_id`, `reciver_city_id`, `reciver_area_id`, `invoice_info`, `promotion_info`, `dlyo_pickup_code`) VALUES ('"
                                        + order_id + "', '" + shop.ID + "', '0', '0', '0', '0', '0', '" + orderRemarks + "', '0', null, null, null, '0', '" + new_addr.data[0].name + "', 'a:6:{s:5:\"phone\";s:11:\"" + new_addr.data[0].mobile + "\";s:9:\"mob_phone\";s:11:\"" + new_addr.data[0].mobile + "\";s:9:\"tel_phone\";s:0:\"\";s:7:\"address\";s:" + addressLength + ":\"" + new_addr.data[0].address + "\";s:4:\"area\";s:0:\"\";s:6:\"street\";s:0:\"\";}', '" + new_addr.data[0].province_id + "', '" + new_addr.data[0].city_id + "', '" + new_addr.data[0].area_id + "', 'a:0:{}', '', null);";
                                        OCM.ExecuteNonSql(sql_order_common);
                                        string sql_order_goods = "INSERT INTO `db_order_goods` (`order_id`, `goods_id`, `goods_name`, `goods_price`, `goods_num`, `goods_image`, `goods_pay_price`, `store_id`, `buyer_id`, `goods_type`, `promotions_id`, `commis_rate`, `gc_id`) VALUES ('"
                                            + order_id + "', '" + goods.goods_id + "', '" + goods.goods_name + "', '" + goods.goods_price + "', '1', '" + goods.goods_image + "', '" + goods.goods_price + "', '" + shop.ID + "', '" + new_user.data.member_id + "', '1', '0', '0', '" + goods.gc_id + "');";
                                        OCM.ExecuteNonSql(sql_order_goods);
                                        string sql_order_pay = "INSERT INTO `db_order_pay` (`pay_sn`, `buyer_id`, `api_pay_state`) VALUES ('" + payCode + "', '" + new_user.data.member_id + "', '0');";
                                        OCM.ExecuteNonSql(sql_order_pay);
                                    }
                                }
                                if (order_id != "" && order_id != "-1")
                                {
                                    Post_Msg pms1 = OCM.WSYUpdateUserBuyCount(new_user.data.member_id);
                                    Post_Msg pms2 = OCM.WSYUpdateAddressCount(new_addr.data[0].id);
                                    ///////////////////////////////////////////////
                                    _logs.Insert(0, new_addr.data[0].name + " " + new_addr.data[0].mobile + " " + new_addr.data[0].province_id + " " + new_addr.data[0].city_id + " " + new_addr.data[0].area_id + " " + new_addr.data[0].address + "\r\n");

                                    this.sr_tb_logs.Text = _logs.ToString();
                                    string _s_time = ((DateTime.Parse(this.sr_dt_time.Value.ToShortDateString()).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                                    string _e_time = ((DateTime.Parse(this.sr_dt_time.Value.AddDays(1).ToShortDateString()).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                                    string _totalStr = OCM.ExecuteMySql("SELECT SUM(order_amount) FROM db_order as o LEFT JOIN db_order_goods as og on o.order_id=og.order_id LEFT JOIN db_order_common as oc on o.order_id=oc.order_id WHERE o.add_time>'" + _s_time + "' and o.add_time<'" + _e_time + "'  and o.order_state in(10,20,30,40);");
                                    string _payStr = OCM.ExecuteMySql("SELECT SUM(order_amount) FROM db_order as o LEFT JOIN db_order_goods as og on o.order_id=og.order_id LEFT JOIN db_order_common as oc on o.order_id=oc.order_id WHERE o.add_time>'" + _s_time + "' and o.add_time<'" + _e_time + "'  and o.order_state in(20,30,40);");
                                    try
                                    {
                                        total = decimal.Parse(_totalStr);
                                    }
                                    catch
                                    {
                                        total = 0;
                                    }
                                    try
                                    {
                                        total_pay = decimal.Parse(this.lb_sr_pay.Text);
                                    }
                                    catch
                                    {
                                        total_pay = 0;
                                    }

                                    count += 1;

                                    _logs.Insert(0, "[" + DateTime.Now + "]成功录入一条订单信息到店铺：[" + shop.Name + "]。\r\n");

                                    this.sr_lb_totalPrice.Text = total.ToString();
                                    this.lb_sr_pay.Text = _payStr.ToString();
                                    this.sr_lb_status.Text = "运行中……";

                                    this.sr_tb_logs.Text = _logs.ToString();

                                    this.sr_lb_count.Text = count.ToString();
                                }
                            }
                            else
                            {
                                _logs.Insert(0, "[" + DateTime.Now + "]获取收货地址失败：" + new_addr.msg + "。\r\n");
                                this.sr_tb_logs.Text = _logs.ToString();
                                post_err_cnt++;
                                if (post_err_cnt > 10)
                                {
                                    this.sr_lb_status.Text = "停止中……";
                                    sr_bgw.CancelAsync();
                                }
                            }
                        }
                        else
                        {
                            _logs.Insert(0, "[" + DateTime.Now + "]获取下单人信息失败：" + new_user.msg + "。\r\n");
                            this.sr_tb_logs.Text = _logs.ToString();
                            post_err_cnt++;
                            if (post_err_cnt > 10)
                            {
                                this.sr_lb_status.Text = "停止中……";
                                sr_bgw.CancelAsync();
                            }
                        }
                    }
                    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    if (bd_cb.Checked != true)
                    {
                        Random rd_sl = new Random();
                        int t_sl = rd_sl.Next(5 * 1000, Int32.Parse(this.tb_jiange.Text) * 1000);
                        System.Threading.Thread.Sleep(t_sl);
                    }
                }
            } while (!worker.CancellationPending);

            this.sr_lb_status.Text = "已停止！";

            this.sr_btn_start.Enabled = true;

            this.sr_btn_stop.Enabled = false;
            
            this.sr_tb_goodIds.Enabled = true;
            
            
        }

        private void sr_bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                this.sr_lb_status.Text = "已停止！";
            }
        }

        private void sr_btn_start_Click(object sender, EventArgs e)
        {
            if (this.sr_tb_goodIds.Text.Length < 1)
            {
                MessageBox.Show("请输入产品ID。");
            }
            else 
            {
                this.sr_lb_status.Text = "系统初始化中……";

                this.sr_bgw.RunWorkerAsync();
            }
            
        }

        private void sr_btn_stop_Click(object sender, EventArgs e)
        {
            this.sr_lb_status.Text = "停止中……";

            sr_bgw.CancelAsync();
        }

        public static string syncAlipay(string _orderSn, string _orderPrice, string _account, string _fullName, string _tradeTime)
        {
            try
            {
                string url = "orderNo=" + _orderSn + "&";
                url = url + "tradeAmount=" + _orderPrice + "&";
                url = url + "otherAccountEmail=" + _account + "&";
                url = url + "otherAccountFullname=" + _fullName + "&";
                url = url + "sourceType=" + 1 + "&"; // 来源:1为531,2为我订花
                url = url + "tradeTime=" + _tradeTime;
                // string formUrl = "http://sync?.qqxhsd.com/api/trade/add";
                string formUrl = "https://alipay.22ca.com/index.php/Api/insertOrder3";
                string formData = url;                               //提交的参数

                //注意提交的编码 这边是需要改变的 这边默认的是Default：系统当前编码
                byte[] postData = Encoding.UTF8.GetBytes(formData);

                // 设置提交的相关参数 
                HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;

                // 提交请求数据 
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                srcString = reader.ReadToEnd();
                string result = srcString;   //返回值赋值
                reader.Close();
                return result;
            }
            catch
            {
                return "error";
            }
        }

        private void bd_cb_CheckedChanged(object sender, EventArgs e)
        {
            if (this.bd_cb.Checked == true)
            {
                this.sr_dt_time.Enabled = true;
            }
            else
            {
                this.sr_dt_time.Enabled = false;

            }
        }

        private void tb_allprice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }
    }
}
